export default function initRating() {
  const $ = window.jQuery;
  
  $.fn.$rateSetVal = function(val, bInput) {
    const integer = +val*2
    if (integer === integer<<0) {
      val = +val
      const $rateContainer = $(this)
      if (!$rateContainer.hasClass('mh-rate')) {
        throw new Error('Not a MH Rating Component')
      }
      $rateContainer.find('.mh-rate-star>div')
        .each(function(i, el) {
          const $radio = $(el)
          const pos = +$radio.attr('aria-posinset')
          
          if (val >= pos) {
            $radio.parent('.mh-rate-star')
              .removeClass('mh-rate-star-zero mh-rate-star-half')
              .addClass('mh-rate-star-full')
          } else if (val > pos - 1) {
            $radio.parent('.mh-rate-star')
              .removeClass('mh-rate-star-zero mh-rate-star-full')
              .addClass('mh-rate-star-half')
          } else {
            $radio.parent('.mh-rate-star')
              .removeClass('mh-rate-star-half mh-rate-star-full')
              .addClass('mh-rate-star-zero')
          }
        })
      
      if (bInput) {
        $rateContainer.find('input').eq(0).val(val)
      }
    } else { throw new Error('Invalid Rating Value') }
  }
  
  $.fn.$rateGetVal = function() {
    const $rateContainer = $(this)
    if (!$rateContainer.hasClass('mh-rate')) {
      throw new Error('Not a MH Rating Component')
    }
    let rate = +($rateContainer.find('input').eq(0).val())
    if (isNaN(rate)) 
      rate = -1
    return rate
  }
  
  $('.mh-rate').each(function(i, el) {
    const $rateContainer = $(el)
    const $inputEl = $rateContainer.find('input').eq(0)
    $rateContainer.find('.mh-rate-star-first, .mh-rate-star-second')
      .on('mouseenter', function(e) {
        const $target = $(this)
        const $radio = $target.parent()
        const pos = +$radio.attr('aria-posinset')
        if ($target.hasClass('mh-rate-star-first')) {
          $rateContainer.$rateSetVal(pos - .5)
        } else {
          $rateContainer.$rateSetVal(pos)
        }
      })
      .on('click', function(e) {
        e.preventDefault();
        
        const $target = $(this)
        const $radio = $target.parent()
        const pos = +$radio.attr('aria-posinset')
        if ($target.hasClass('mh-rate-star-first')) {
          $rateContainer.$rateSetVal(pos - .5, true)
        } else {
          $rateContainer.$rateSetVal(pos, true)
        }
      })
      
    $rateContainer.on('mouseleave', function(e) {
      $rateContainer.$rateSetVal($rateContainer.$rateGetVal())
    })
    
    $rateContainer.$rateSetVal(0, true)
  })
}